<?php

defined('SYSPATH') or die('No direct script access.');

class Controller_Admin_News extends Controller {

    public function action_list() {
        Session::instance()->set('here', 'here');
        $pagination_arr = Paginationhelp::get_data('new', 'id_news');
        $news_category = ORM::factory('news_category')->find_all()->as_array();
        foreach ($news_category as $key => $value) {
            $news_categories[$value->id_category] = $value->name;
        }
        
        $data = array(
            'result' => $pagination_arr['data'],
            'news_categories' => $news_categories,
            'page_view' => $pagination_arr['pagination']
        );

        $view = Viewer::display('admin/content/news_list', $data);
        $this->response->body($view);
    }

    public function action_add() {
        Session::instance()->set('here', 'here');
        $news_categories = News::instances()->get_categories();
        if ($_POST) {
            $_POST['addtime'] = time();
            $_POST['updatetime'] = time();
            $new = News::instances()->set($_POST);
            if ($new) {
                Message::set('新闻添加成功！');
                Request::current()->redirect(URL::base() . 'admin/news/add');
            }
        }
        $content_data = array('news_categories' => $news_categories);
        $view = Viewer::display('admin/content/news_add', $content_data);
        $this->response->body($view);
    }

    public function action_edit() {
        $id_news = $this->request->param('id');
        if ($_POST) {
            $_POST['updatetime'] = time();
            $new = NEWS::instances($id_news)->update($_POST);
            if ($new) {
                Message::set('新闻编辑成功！');
                Request::current()->redirect(URL::base() . 'admin/news/edit/' . $id_news);
            }
        }
        $new = News::instances($id_news)->get();
        $news_categories = News::instances()->get_categories($new['id_category']);
        $view = Viewer::display('admin/content/news_edit', array('data' => $new, 'news_categories' => $news_categories));
        $this->response->body($view);
    }

    public function action_delete() {
        $id_news = $this->request->param('id');
        $flag = News::instances($id_news)->delete();
        if ($flag) {
            Message::set('新闻删除成功');
            Request::current()->redirect(URL::base() . 'admin/news/list');
        } else {
            Message::set('新闻删除失败', 'error');
            Request::current()->redirect(URL::base() . 'admin/news/list');
        }
    }

}